package 数组.滑动窗口.水果成篮;

import java.util.*;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/11 17:28
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {1,0,1,4,1,4,1,2,3};
        System.out.println(totalFruit(arr));
    }

  /*  public static int totalFruit(int[] fruits) {
        //水果种类
        int specie = 2;
        int slowIndex = 0;
        Map<Integer,Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        for (int fastIndex = 0; fastIndex < fruits.length; fastIndex++) {
            if (map.containsKey(fruits[fastIndex])){
                Integer num = map.get(fruits[fastIndex]);
                map.put(fruits[fastIndex],++num);
            }else if (!map.containsKey(fruits[fastIndex]) && specie > 0){
                map.put(fruits[fastIndex],1);
                specie--;
            }

            if (specie == 0 && !map.containsKey(fruits[fastIndex])){
                list.add(getTotalNumInMap(map));
                int fruit = fruits[slowIndex];
                map.remove(fruits[slowIndex]);
                map.put(fruits[fastIndex],1);
                while (fruits[slowIndex] == fruit){
                    slowIndex++;
                }
                //specie++;
            }
        }
        list.add(getTotalNumInMap(map));
        return Collections.max(list);
    }

    public static int getTotalNumInMap(Map<Integer,Integer> map){
        int totalNum = 0;
        Collection<Integer> values = map.values();
        Iterator<Integer> iterator = values.iterator();
        while (iterator.hasNext()){
            totalNum += iterator.next();
        }
        return totalNum;
    }*/


    //滑动窗口
    public static int totalFruit(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<>();

        int left = 0, ans = 0;
        for (int right = 0; right < n; ++right) {
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            while (cnt.size() > 2) {
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

}
